<!DOCTYPE html>
<html lang="zh-CN">
<head>
     <meta charset="UTF-8">
    <title>WebRTC Video Call</title>
    <style>
        video {
            width: 45%;
            height: auto;
            border: 1px solid black;
            margin: 5px;
        }
    </style>
</head>
<body>
    <h1>WebRTC Video Call</h1>
    
    <div style="display: flex;">    

        <div style="width:50%">
            <div>本地的视频</div>
            <video style="width: 400px;height: 400px;" id="localVideo" autoplay ></video>
        </div>
        

        <div style="width:50%">

            <div>远程的视频</div>
            <video style="width: 400px;height: 400px;"  id="remoteVideo" autoplay muted>remoteVideo</video>
        </div>
    </div>

     
    <script>
        const localVideo = document.getElementById('localVideo');
        const remoteVideo = document.getElementById('remoteVideo');

        let randomNumber =  Math.floor(Math.random() * (1000 + 1));

        // 部署到服务器后放开注释
        // const peerConnectionConfig = {
        //     iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
        // };
        // let peerConnection = new RTCPeerConnection(peerConnectionConfig);


        let peerConnection = new RTCPeerConnection();
        let localStream;
        let remoteStream;
        let signalingSocket;

        async function start() {

                // 加载本地媒体流
                localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
                localVideo.srcObject = localStream;
                
                // 加载远程
                remoteStream = new MediaStream;
                remoteVideo.srcObject = remoteStream;

                //  本地视频流添加到peerConnection中
                localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));

                // 加载远程的视频流
                peerConnection.ontrack = (event) => {
                    event.streams[0].getTracks().forEach((track)=>{
                        remoteStream.addTrack(track);
                    })
                };

                signalingSocket = new WebSocket('ws://localhost:8080/ws');
                

                signalingSocket.onopen = async (event) => {
                        console.log("local random:",randomNumber);
                      
                        peerConnection.onicecandidate = (event) => {
                            // console.log("onicecandidate:",event);
                            if (event.candidate) {
                                signalingSocket.send(JSON.stringify({ type: 'candidate', candidate: event.candidate,rand:randomNumber }));
                            }
                        };

                        const offer = await peerConnection.createOffer();
                        await peerConnection.setLocalDescription(offer);
                        signalingSocket.send(JSON.stringify({ type: 'offer', offer ,rand:randomNumber }));
                };

                //  监听消息
                signalingSocket.onmessage = function(event) {
                    handleSignalingMessage(event);
                };
            
        }

        function handleSignalingMessage(messageEvent) {
            const message = JSON.parse(messageEvent.data);
            console.log("Received message:",message)
            if(message.rand === randomNumber){
                return
            }
            if (message.type === 'offer') {
                handleOffer(message.offer);
            } else if (message.type === 'answer') {
                handleAnswer(message.answer);
            } else if (message.type === 'candidate') {
                handleCandidate(message.candidate);
            }
        }

        // B 端接收 A端发过来的offer
        async function handleOffer(offer) {
                await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
                const answer = await peerConnection.createAnswer();
                await peerConnection.setLocalDescription(answer);
                signalingSocket.send(JSON.stringify({ type: 'answer', answer ,rand:randomNumber}));
        }

        // A端接收B端发过来的answer
        async function handleAnswer(answer) {
              await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
        }

        async function handleCandidate(candidate) {
                await peerConnection.addIceCandidate(candidate);
        }

        start();
    </script>
</body>
</html>
